import {
  login,
  logout,
  getInfo,
  socialLogin,
  socialBindLogin,
  smsLogin,
} from "@/api/login";
import { getClockdown } from "@/api/bpm/activity";
import { setToken, removeToken, getStoreId, removeStoreId } from "@/utils/auth";
import { Notification } from "element-ui";
var MsgTypetimes;
const user = {
  state: {
    id: 0, // 用户编号
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
    msgTotal: 0,
    deptId: "",
    deptName: "",
    stores: [],
    storesItem: {},
  },

  mutations: {
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_NICKNAME: (state, nickname) => {
      state.nickname = nickname;
    },
    SET_DEPTID: (state, deptId) => {
      state.deptId = deptId;
    },
    SET_DEPTNAME: (state, deptName) => {
      state.deptName = deptName;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },

    SET_MSGTOTAL: (state, msgTotal) => {
      state.msgTotal = msgTotal;
    },

    SET_DElMSGTOTAL: (state) => {
      state.msgTotal = state.msgTotal -= 1;
    },

    SET_STORES: (state, STORES) => {
      state.stores = STORES;
    },
    SET_STOREITEM: (state, STOREITEM) => {
      state.storesItem = STOREITEM;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      console.log("userInfo", userInfo);
      const username = userInfo.mobile.trim();
      const password = userInfo.password.trim();
      const captchaVerification = userInfo.captchaVerification;
      const socialCode = userInfo.socialCode;
      const socialState = userInfo.socialState;
      const socialType = userInfo.socialType;
      const token = userInfo.smsToken;
      const smsCode = userInfo.smsCode;
      return new Promise((resolve, reject) => {
        login(
          username,
          password,
          captchaVerification,
          socialType,
          socialCode,
          socialState
          // token,
          // smsCode
        )
          .then((res) => {
            const { code, data } = res;
            setToken(data);
            resolve(res);
            // 设置 token
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 社交登录
    SocialLogin({ commit }, userInfo) {
      const code = userInfo.code;
      const state = userInfo.state;
      const type = userInfo.type;
      return new Promise((resolve, reject) => {
        socialLogin(type, code, state)
          .then((res) => {
            res = res.data;
            // 设置 token
            setToken(res);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 短信登录
    SmsLogin({ commit }, userInfo) {
      const username = userInfo.mobile.trim();
      const smsCode = userInfo.smsCode;
      console.log("45454");

      return new Promise((resolve, reject) => {
        smsLogin(username, smsCode)
          .then((res) => {
            console.log("777888", res);
            // 设置 token
            setToken(res.data);
            console.log("99999", res);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    GetInfo({ commit, dispatch, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // 没有 data 数据，赋予个默认值
            if (!res) {
              res = {
                data: {
                  storeDTOS: [],
                  roles: [],
                  user: {
                    id: "",
                    avatar: "",
                    userName: "",
                    nickname: "",
                    deptId: "",
                    deptName: "",
                  },
                },
              };
            }

            const { data } = res;

            const user = data.user;
            const avatar =
              user.avatar === "" || user.avatar == null
                ? require("@/assets/images/profile.jpg")
                : user.avatar;
            if (data.roles && data.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", data.roles);
              commit("SET_PERMISSIONS", data.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_ID", user.id);
            commit("SET_NAME", user.userName);
            commit("SET_NICKNAME", user.nickname);
            commit("SET_DEPTID", user.deptId);
            commit("SET_DEPTNAME", user.deptName);
            commit("SET_AVATAR", avatar);

            commit("SET_STORES", data.storeDTOS);

            dispatch("MessageType");
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            removeStoreId();
            resolve();
            clearInterval(MsgTypetimes);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    MessageType() {
      console.log("a");
      MsgTypetimes = setInterval(() => {
        getClockdown({})
          .then((res) => {
            const { code, data } = res;
            console.log(code, data);
            if (code === 0 && data.length) {
              let arry = data.map((item) => {
                return (
                  "<p>[" +
                  item.roomName +
                  "]-" +
                  item.nickname +
                  (item.stageName ? "(" + item.stageName + ")" : "") +
                  "</p>"
                );
              });
              Notification({
                title: "技师下钟提醒",
                dangerouslyUseHTMLString: true,
                message: arry.join(" "),
              });
            }
          })
          .catch((err) => {});
      }, 10000);
    },
  },
};

export default user;
